<template>
  <div class="container">
    <el-dialog
      title="新增角色"
      :visible="visible"
      width="500px"
      @close="onCancel"
    >
      <el-form ref="formRef" :rules="formRules" :model="formData">
        <el-form-item label="角色名称" label-width="100px" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="启用" label-width="100px">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" label-width="100px" prop="description">
          <el-input v-model="formData.description" type="textarea" />
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button type="danger" @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleApi } from '@/api/role'

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      formData: {
        name: '', // 角色名称
        description: '', // 角色描述
        state: 1 // 角色状态
      },
      formRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit() {
      await this.$refs.formRef.validate()
      await addRoleApi(this.formData)
      this.$message.success('新增角色成功')
      this.onCancel()
      this.$emit('updatedepts')
    },
    onCancel() {
      this.$emit('update:visible', false)
      this.$refs.formRef.resetFields()
    }
  }
}
</script>
